<?php

namespace app\apiv1\controller;

use service\DataService;
use service\WechatService;
use think\Error;
use think\Validate;
use think\Db;
use think\Facade\Cache;

/**
 * 应用入口控制器
 * @author Anyon <zoujingli@qq.com>
 */
class Index extends Base
{

    public function profile()
    {
		 $user = $this->commonService->setUserID($this->wx_user_id)->getUserLevel();
        $user['account_money'] = reserve_num($user['account_money']);
        $user['integ'] = reserve_num($user['integral'],2);
        $user['integral'] = reserve_num($user['integral'],2) + reserve_num($user['spread_integral'],2) + reserve_num($user['spread_used'],2);

        $user['spread_integral'] = reserve_num($user['spread_integral'],2);
        $user['total_share_integral'] = Db::name('bags_log')->where(['extends' => 'reduce_spread_integral', 'uid' => $this->wx_user_id])->sum('money');
        if(!empty(floor($user['integral']))){
            $list = Db::table('sys_lettery')->where('shuliang','<=',floor($user['integral']))->order('shuliang desc')->find();
        }
        if(!empty($list)){
            $user['member_level'] = $list['id'];
        }else{
            $user['member_level'] = '0';
        }
        
         $fansInfo = WechatService::WeChatUser()->getUserInfo($user['openid']);

    	if($fansInfo['subscribe']!=$user['subscribe'])
    	{
    		Db::name('store_member')->where(['id' => $this->wx_user_id])->update(['subscribe' => $fansInfo['subscribe']]);
    		$user['subscribe']=$fansInfo['subscribe'];
    	}


        if ($user) {
            $this->success($user);
        } else {
            $this->error('请登录', '', 999);
        }
    }

    public function getHalf(){
        $half = Db::name('store_member')->where('id',$this->wx_user_id)->field('is_half_price')->find();
        if ($half){
            $this->success($half);
        }else{
            $this->error('获取失败','',999);
        }
    }


 


    public function getTeamByUserList()
    {
        $underTeamIds = Db::query("SELECT id,member_level FROM `store_member` WHERE FIND_IN_SET($this->wx_user_id,first_leader)");
        if (count($underTeamIds) <= 0) $this->error('没有下级');
        $userList = Db::name('store_member a')
            ->join('sys_level b','a.member_level = b.id')
            ->where('a.id', 'in', implode(',', array_column($underTeamIds, 'id')))
            ->page($this->page, $this->max_page_num)
            ->select();
        $this->success($userList);
    }


    //参数
    public function getUserTeamparameter()
    {
        //团队粉丝
        $par['fensi'] = Db::query("SELECT count(*) as sub_person_count  FROM `store_member` WHERE FIND_IN_SET($this->wx_user_id,first_leader)")[0]['sub_person_count'];
        $par['zfensi'] = Db::name('store_member')->where(['first_leader' => $this->wx_user_id])->where("member_level",'=',2)->count();
        $drive = Db::name('store_member')->where(['first_leader' => $this->wx_user_id])->where('member_level', '=', 1)->count();
        $par['zhitui'] = $drive;
        $this->success('', $par);
    }


    //申请保养
    public function applyFullPrice()
    {
        $type = input('post.type');
        if (!$type) $this->error('缺少类型');  //is_full_price is_half_price
        if ($this->wx_user[$type] == 2) $this->error('已申请,无需重复提交');

        Db::startTrans();

        $car = Db::name('store_member')->where('id',$this->wx_user_id)->field('member_level,sheng,carid,shop_id')->find();

        if ($type == 'is_half_price' && $car['member_level'] !== 2){
            $this->error('用户没有权限兑换');
            die;
        }
        $carid = $car['sheng'] . $car['carid'];

        $insertData = [
            'uid' => $this->wx_user_id,
            'shopid' => $car['shop_id'],
            'addtime' => time(),
            'type' => $type,
            'carid' => $carid
        ];
        if ($type == 'is_half_price') {
            $spread_integral = sysconf('spread_integral');
            if ($this->wx_user['spread_integral'] < $spread_integral) $this->error('积分不足');
            $res[] = mlog($this->wx_user_id, 'spread_integral',  -$spread_integral, '兑换半价保养扣除' . $spread_integral . '积分', 'reduce_spread_integral');
//            Db::name("store_member")->where('id',$this->wx_user['spread_integral'])->setInc('spread_integral',2);

            $insertData['num'] = sysconf('spread_integral');
        } else {
            $insertData['num'] = sysconf('give_integral');
        }

        $res[] = Db::name('store_apply_record')->insert($insertData);
        $res[] = Db::name('store_member')->where(['id' => $this->wx_user_id])->update([$type => 2]);
        if (check_arr($res)) {
            Db::commit();
            $this->error('申请成功');
        } else {
            Db::rollback();
            $this->error('申请全价保养失败');
        }
    }


    //获取全价记录
    public function getFullPriceRecord()
    {
        $res = Db::name('store_apply_record')
            ->where(['type' => 'is_full_price','status'=>1,'uid'=>$this->wx_user_id])
            ->page($this->page, $this->max_page_num)
            ->order('id desc')
            ->select();
        foreach($res as &$v){
            $v['addtime'] = date('Y.m.d',$v['addtime']);
            $v['status'] = get_order_status($v['status']);
        }
        $this->success('',$res);
    }

    //获取发放
    public function getGiveFullPriceRecord()
    {
        $res = Db::name('bags_log')
            ->where(['extends'=>'give_integral','uid'=>$this->wx_user_id])
            ->page($this->page, $this->max_page_num)
            ->order('id desc')
            ->select();
        foreach($res as &$v){
            if ($v['money'] < 0){
                $v['money'] = -$v['money'];
            }
            $v['create_time'] = date('Y.m.d',$v['create_time']);
        }
        $this->success('',$res);
    }



    public function getSpreadRecord()
    {
        $res = Db::name('bags_log')
            ->where(['extends'=>'share_spread_integral','uid'=>$this->wx_user_id])
            ->page($this->page, $this->max_page_num)
            ->order('id desc')
            ->select();
        foreach($res as &$v){
            if ($v['money'] < 0){
                $v['money'] = -$v['money'];
            }
            $v['create_time'] = date('Y.m.d',$v['create_time']);
        }
        $this->success('',$res);
    }

//分享记录
    public function getShareIntegralRecord()
    {
        $res = Db::name('store_apply_record')
            ->where(['type' => 'is_half_price','uid'=>$this->wx_user_id])
            ->page($this->page, $this->max_page_num)
            ->order('id desc')
            ->select();
        foreach($res as &$v){
            $v['addtime'] = date('Y.m.d',$v['addtime']);
            $v['status'] = get_order_status($v['status']);
        }
        $this->success('',$res);
    }



    public function getAllIntegralRecord()
    {
        $res = Db::name('bags_log')
            ->where(['uid'=>$this->wx_user_id])
            ->page($this->page, $this->max_page_num)
            ->order('id desc')
            ->select();
        foreach($res as &$v){
            if ($v['money'] < 0){
                $v['money'] = -$v['money'];
            }
            $v['create_time'] = date('Y.m.d H:i:s',$v['create_time']);
        }
        $this->success('',$res);
    }





    public function qrcode()
    {
        $share  = 'http://' . $_SERVER['HTTP_HOST'] . '/?first_leader=' . $this->wx_user['openid'];
        $url = 'http://api.k780.com:88/?app=qr.get&data=' . urlencode($share);
        $qrcode = db('store_member')->where(array('openid' => $this->wx_user['openid']))->value('qrcode');
        //$qrcode = db('store_member')->where(array('id' => $this->wx_user['id']))->value('qrcode');
		//if (empty($qrcode)) {
		if( 1 == 1 ) {
			$file = 'upload/' . md5(time() . $this->user['username']) . '.png';
			if (file_put_contents('./' . $file, file_get_contents($url))) {
				$appRoot = request()->root(true); // 去掉参数 true 将获得相对地址
				$uriRoot = preg_match('/\.php$/', $appRoot) ? dirname($appRoot) : $appRoot;
				$file = $uriRoot . '/' . $file;
				Db::name("store_member")->where("openid", $this->wx_user['openid'])->update([
					'qrcode' => $file,
				]);
				// response($file);
				$this->success('', [
					'url' =>$share,
					'qrcodeUrl' => $file,
				]);
			}
		}
        $this->success('', [
            'url' =>$share,
            'qrcodeUrl' => $qrcode,
           
        ]);


       /* $contentUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/?first_leader=' . $this->wx_user['openid'];
        $h5Url = "http://h5ip.cn/index/api?format=json&url=" . urlencode($contentUrl);
        $remote_url = json_decode(file_get_contents($h5Url), true);
        // cogetTransCatede ??
        if ($remote_url['code'] == 0) {
            $imgUrl = '/static/upload/' . md5($this->wx_user['id'] . $this->wx_user['phone']) . '.png';
            $file = ROOT_PATH . $imgUrl;
            makeQrcode($remote_url['short_url'], $file);
            $this->success(['qrcodeUrl' => 'http://' . $_SERVER['HTTP_HOST'] . $imgUrl, 'linkUrl' => $remote_url['short_url']]);
        }*/

    }


    public function getMaintainRecord()
    {
        /*$maintainRecord = Db::name("store_member a")
            ->field('c.*')
            ->join("es_maintain_record c", "a.id = c.uid")
            ->where("c.uid", $this->wx_user_id)
            ->page($this->page, $this->max_page_num)
            ->order('c.create_time desc')
            ->select();*/
        $maintainRecord = Db::name("store_member")
            ->alias('a')
            ->join('store_apply_record b',"a.id = b.uid")
            ->where('b.uid',$this->wx_user_id)
            ->page($this->page,$this->max_page_num)
            ->field('a.carid,a.sheng,b.*')
            ->order('b.addtime desc')
            ->select();

        foreach ($maintainRecord as &$v) {
            $v['car'] = $v['sheng'] . $v['carid'];
            $v['create_time'] = format_time($v['addtime']);
        }
        if (empty($maintainRecord)) $this->error('没有更多数据');
        $this->success('', $maintainRecord);
    }


    //用户是否实名认证过
    public function getProfileFlag()
    {
        $userInfo = Db::name('store_member_idcard')->where(['uid' => $this->wx_user_id])->find();
        if (!empty($userInfo)) {
            $userInfo['status'] == 0 && $this->success('审核中,请耐心等待', '', 4);
            $userInfo['status'] == 2 && $this->success('审核失败,请重新提交审核', '', 3);
            $this->success('实名认证已经通过,无需重复提交');
        } else {
            $this->error('用户还没有认证');
        }
    }

    //实名认证
    public function idcard()
    {
        $data = input('post.');
        $validate = Validate::make([
            'truename' => 'require',
            'idcard' => 'require|idCard',
            'zidcardimg' => 'require',
            'fidcardimg' => 'require',
//            'sidcardimg' => 'require',
//            'code' => 'require',
        ], [
            'truename.require' => '真实姓名不能为空！',
            'idcard.require' => '身份证号不能为空！',
            'idcard.idCard' => '身份证号格式不正确！',
            'zidcardimg.require' => '请上传正面身份证照片!',
            'fidcardimg.require' => '请上传反面身份证照片！',
//            'sidcardimg.require' => '请1上传手持身份证照片！',
//            'code.require' => '验证码不能为空!',

        ]);
        $validate->check($data) || $this->error($validate->getError());
//        $data['code'] != $this->getSmsCode('code',$data['phone']) && $this->error('短信验证码错误:(');
        $data['uid'] = $this->wx_user_id;
        $data['addtime'] = time();
        $data['status'] = 0;
        $idcard = Db::name('store_member_idcard')->where(['uid' => $this->wx_user_id])->find();

        if (!empty($idcard)) {
            if ($idcard['status'] == 1) {
                $this->error('您的身份验证已经通过,请勿重复提交');
            } elseif ($idcard['status'] == 0) {
                $this->error('您的身份验证正在审核当中');
            }
        }

        Db::startTrans();
//        $fp = fopen(ROOT_PATH . "./" . __FUNCTION__ . ".txt", "w+");
//        if (flock($fp, LOCK_EX | LOCK_NB)) {
        $res[] = DataService::other_save('store_member_idcard', $data, ['uid' => $this->wx_user_id]);
//            flock($fp, LOCK_UN);
//        }
        if (check_arr($res)) {
            Db::commit();
//            fclose($fp);
            $this->success();
        } else {
            Db::rollback();
            $this->error();
        }
    }

    //实名认证列表
    public function idcardlist()
    {
        $list = Db::name('store_member_idcard')->where(['uid' => $this->wx_user_id])->find();
        $this->success($list);
    }

    //新闻轮播图
    public function business()
    {
        $list = Db::name('es_article')->where(['type' => 'news_banner', 'status' => 1])->select();
        foreach ($list as $k => &$v) {
            $v['img'] = str_replace('http://' . $_SERVER['HTTP_HOST'], '', $v['img']);
        }
        $this->success($list);
    }

    //公告   faq 常见问题   fingerpost 新手指南  about 关于我们
    public function notice()
    {
        $param = input('param.');
        $res = Db::name('es_article')->where(['type' => $param['type']])->page($this->page, $this->max_page_num)->order('id desc')->select();
        foreach ($res as &$v) {
            $v['title'] = mb_substr($v['title'], 0, 10, 'utf-8');
            if ($v['type'] == 'about' || $v['type'] == 'faq') {
            } else {
                $v['content'] = str_replace('&nbsp;', '', mb_substr(strip_tags($v['content']), 0, 30, 'utf-8'));
            }
            $v['addtime'] = format_time($v['addtime']);
        }
        $this->success($res);
    }

    //公告详情
    public function detail()
    {
        $param = input('param.');
        $res = Db::name('es_article')->where(['id' => $param['id']])->find();
        $res['addtime'] = format_time($res['addtime']);
        $this->success($res);
    }


    public function bank()
    {
        $data = input('post.');
        $validate = Validate::make([
            'truename' => 'require',
            'bankname' => 'require',
            'bankcard' => 'require',
            'banksite' => 'require',
//            'code' => 'require',
        ], [
            'truename.require' => '真实姓名不能为空！',
            'bankname.require' => '银行卡名不能为空！',
            'bankcard.require' => '银行卡号不能为空！',
            'banksite.require' => '银行开户地址不能为空!',
//            'code.require' => '验证码不能为空!',
        ]);
        $validate->check($data) || $this->error($validate->getError());

        if (!preg_match('/^([1-9]{1})(\d{14}|\d{18}|\d{15}|\d{17})$/', $data['bankcard'])) {
            $this->error('银行卡号格式不正确!!');
        }
        $bantrue = Db::name('store_member_idcard')->where(['uid' => $this->wx_user_id])->value('truename');
        $data['truename'] != $bantrue && $this->error('银行卡真实姓名需要与实名认证姓名相同');
        $data['uid'] = $this->wx_user_id;
        $data['addtime'] = time();
        $data['code'] != $this->getSmsCode('code', $this->wx_user['phone']) && $this->error('短信验证码错误:(');
        Db::startTrans();
        unset($data['code']);
        $res[] = DataService::other_save('store_member_bank', $data, ['uid' => $this->wx_user_id]);
        if (check_arr($res)) {
            Db::commit();
            $this->success();
        } else {
            Db::rollback();
            $this->error();
        }
    }

    //银行卡列表
    public function banklist()
    {
        $list = Db::name('store_member_bank')->where(['uid' => $this->wx_user_id])->find();
        $this->success($list);
    }

    //更改密码

    public function password()
    {
        $post = input('post.');
        !$post['password'] && $this->error('登录密码不能为空');
        !$post['repassword'] && $this->error('确认新密码不能为空');
        !$post['code'] && $this->error('验证码不能为空');
        if ($post['password'] != $post['repassword'])
            $this->error('两次登录密码不一致');
        $post['code'] != $this->getSmsCode('code', $this->wx_user['phone']) && $this->error('短信验证码错误:(');
        $res = Db::name('store_member')->where(['id' => $this->wx_user_id])->update(['password' => md5($post['password'])]);
        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }


    //更改支付密码

    public function paypassword()
    {
        $post = input('post.');
        !$post['paypassword'] && $this->error('支付密码不能为空');
        !$post['repaypassword'] && $this->error('确认新支付密码不能为空');
        !$post['code'] && $this->error('短信验证码不能为空');
        if ($post['paypassword'] != $post['repaypassword'])
            $this->error('两次支付密码不一致');
        $post['code'] != $this->getSmsCode('code', $this->wx_user['phone']) && $this->error('短信验证码错误:(');
        $res = Db::name('store_member')->where(['id' => $this->wx_user_id])->update(['paypassword' => md5($post['paypassword'])]);
        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

    public function payment()
    {
        $post = input('post.');
        !$post['payment'] && $this->error('不能为空');
//        !$post['paymentimg'] && $this->error('二维码图片不能为空');
        !$post['code'] && $this->error('验证码不能为空');
        $post['addtime'] = time();
        !$post['type'] && $this->error('请传类型');
        $post['uid'] = $this->wx_user_id;
//        input('post.code') != $this->getSmsCode('code', $this->wx_user['phone']) && $this->error('短信验证码错误:(');
        $res = DataService::other_save('store_member_payment', $post, ['uid' => $this->wx_user_id, 'type' => $post['type']]);
        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

    public function paymentlist()
    {
        $param = input('param.');
        if ($param['type'] == 1) {
            $res = Db::name('store_member_payment')->where(['uid' => $this->wx_user_id, 'type' => 1])->find();
        } else {
            $res = Db::name('store_member_payment')->where(['uid' => $this->wx_user_id, 'type' => 2])->find();
        }
        $this->success($res);
    }


    //收益明细
    public function detailed()
    {
        $teamUserList = Db::name("store_member a")
            ->field('a.*,c.title')
            ->join("sys_level c", "c.id = a.member_level")
            ->where("a.first_leader", $this->wx_user_id)
            ->page($this->page, $this->max_page_num)
            ->order('a.member_level desc')
            ->select();
        foreach ($teamUserList as &$v) {
            $v['create_at'] = explode(' ', $v['create_at'])[0];
            $v['is_identity'] = Db::name('store_member_idcard')->where(['uid' => $v['id']])->find() ? 1 : 0;
        }
        $this->success('', $teamUserList);
    }

    //留言
    public function message()
    {
        $data = input('param.');
        !$data['content'] && $this->error('请输入您要留言的内容');
        !$data['image'] && $this->error('请上传图片');

        $res = Db::name('es_leave')->insert([
            'uid' => $this->wx_user_id,
            'image' => $data['image'],
            'status' => 0,
            'content' => $data['content'],
            'create_time' => time(),
        ]);

        if ($res) {
            $this->success('留言成功');
        } else {
            $this->error('留言失败');
        }
    }

    /***************************************C2C开始*******************************************************/
    // type 1买入  2 卖出
    // status 1 等待中  2 匹配,确认打款中  3 完成
    //获取自己的买卖交易记录
    public function getBuyOutOrder()
    {
        $result = Db::name('store_order_c2c a')
            ->field('a.*,b.title')
            ->join("store_order_interval b", "a.interval_id = b.id")
            ->where(['a.mid' => $this->wx_user_id])
            ->where('status', 'not in', '3,5,7,10')
            ->page($this->page, $this->max_page_num)
            ->order('a.create_at desc')
            ->select();
        foreach ($result as &$v) {
            $v['status'] = get_c2c_order_status($v['status']);
        }
        $this->success($result);
    }

    //获取自己已经完成订单
    public function getHistoryOrder()
    {
        $result = Db::name('store_order_c2c a')
            ->field('a.*,b.title')
            ->join("store_order_interval b", "a.interval_id = b.id")
            ->where(['a.mid' => $this->wx_user_id])
            ->where('a.status', 'in', '3,5,10')
            ->page($this->page, $this->max_page_num)
            ->order('a.create_at desc')
            ->select();
        //TODO 遍历status
        foreach ($result as &$v) {
            $v['status'] = get_c2c_order_status($v['status']);
        }
        $this->success($result);
    }

    //获取别人卖出的订单
    public function getOtherPayOutOrder()
    {
        if (sysconf('is_show_sell') == 1) {
            $result = Db::name('store_order_c2c a')
                ->field('a.*,b.title')
                ->join("store_order_interval b", "a.interval_id = b.id")
                ->where(['a.type' => 2, 'status' => 1])
                ->where('mid', 'not in', $this->wx_user_id)
                ->page($this->page, $this->max_page_num)
                ->order('a.create_at desc')
                ->select();
            foreach ($result as &$v) {
                $v['real_price'] = reserve_num($v['real_price']);
                $v['status'] = get_c2c_order_status($v['status']);
            }
            $this->success($result);
        } else {
            $this->success([]);
        }

    }

    //获取交易分类和当前PDR价钱
    public function getTransCate()
    {
        $result['select_list'] = Db::name("store_order_interval")->order('sort asc')->select();
        $result['pdr_money'] = sysconf('pdr_money');
        $this->success($result);
    }

    //买入PDR和 卖出PDR
    public function buyOrderOutOrInto()
    {
        $data = input('post.');
        $orderId = input('post.orderid', 0);
        $validate = Validate::make([
            'type' => 'require',
            'interval_id' => 'require',
            'num' => 'require',
//            'real_price' => 'require',
        ], [
            'type.require' => '买卖类型不能为空1--买入 2--卖出',
            'interval_id.require' => '买入区间不能为空',
            'num.require' => '买入数量不能为空',
//            'real_price.require' => '买入总价不能为空',
        ]);
        $validate->check($data) || $this->error($validate->getError());
        $res = [TRUE];
        $pay_server_money = $data['num'] * sysconf('pdr_money'); //服务端验证money
//        $pay_server_money != $data['real_price'] && $this->error('非法操作,价格');


        $data['num'] > 5000 && $this->error('操作数量上限5000');
        $payment_info = Db::name("store_member_payment")->where(['uid' => $this->wx_user_id])->find();
        !$payment_info && $this->error('请完善打款信息', '', -4002);
        if ($orderId > 0) {
            $intervalInfo = Db::name('store_order_interval')->where(['id' => $data['interval_id']])->find();
        } else {
            $intervalInfo = Db::name('store_order_interval')->where(['title' => $data['interval_id']])->find();
        }

        if ($intervalInfo['id'] == 34) {
            $data['num'] % 10 != 0 && $this->error('操作数量必须是10的倍数');
            $maxCount = Db::name('store_order_c2c')->where(['mid' => $this->wx_user_id, 'interval_id' => 34])->count();
            if ($data['type'] == 1) {
                if ($maxCount >= 1) {
                    $this->error('只能购买一次激活专区');
                }
            }
//        if($data['type'] == 1){
//            if (!in_array($data['num'], [100, 300, 500])) {
//                $this->error('激活专区只能购买100,300,500');
//            }
//        }elseif($data['type'] == 2){
//            if (!in_array($data['num'], [100, 300, 500])) {
//                $this->error('激活专区只能卖出100,300,500');
//            }
//        }

        } else {
            $data['num'] % 100 != 0 && $this->error('操作数量必须是100的倍数');
            //M2
            if ($data['num'] >= $intervalInfo['min_value'] && $data['num'] <= $intervalInfo['max_value']) {

            } else {
                $this->error("{$intervalInfo['title']}限制{$intervalInfo['min_value']}-{$intervalInfo['max_value']}区间");
            }
        }

        $arr = [
            'type' => $data['type'],
            'mid' => $this->wx_user_id,
            'interval_id' => $intervalInfo['id'],
            'order_no' => $this->wx_user_id . rand(100000, 999999) . time(),
            'num' => $data['num'],
            'price' => $pay_server_money / $data['num'],
            'real_price' => $pay_server_money,
            'other_order_id' => $orderId
        ];
        Db::startTrans();
        $flagOrderExist = Db::name("store_order_c2c")->where(['type' => $data['type'], 'mid' => $this->wx_user_id])->where('status', 'in', '1,2')->find();
        if ($flagOrderExist > 0) {
            $this->error('有一笔订单正在交易中');
        }
        if ($data['type'] == 2) {
            $sell_pdr_bond_pdrs = $data['num'] * sysconf('sell_pdr_bond_pdrs') / 100;
            if ($sell_pdr_bond_pdrs && $this->wx_user['pdrs'] < $sell_pdr_bond_pdrs) $this->error("PDRS不足,此次卖出需要消耗PDRS{$sell_pdr_bond_pdrs}");

            $real_cert = Db::name('store_member_idcard')->where(['uid' => $this->wx_user_id, 'status' => 1])->find(); //当前用户是否实名认证
            !$real_cert && $this->error('您还没有实名认证', '', -4001);
            $todayTrans = Db::name("store_order_c2c")->where(['type' => 1, 'mid' => $this->wx_user_id])->whereTime('create_at', 'd')->count();
            if ($todayTrans >= 1) $this->error('24小时内不能进行卖出');
            if ($this->wx_user['member_level'] > 2) {
            } else {
                if ($this->wx_user['member_level'] == 1) {
                    $this->error('临时会员不能卖出');
                }
                if ($intervalInfo['id'] == 34) {
                    $this->error('星级才能卖出');
                }

            }
            //卖出
            if ($data['num'] > $this->wx_user['account_money']) {
                $this->error('账户PDR不足');
            }
            if ($sell_pdr_bond_pdrs > 0) {
                $res[] = mlog($this->wx_user_id, 'pdrs', -$sell_pdr_bond_pdrs, '卖出PDR,消耗PDRS' . $sell_pdr_bond_pdrs, 'sell_pdrs_reduce');
            }

            $res[] = mlog($this->wx_user_id, 'account_money', -$data['num'], '卖出PDR' . $data['num'] . '个', 'sell_pdr');
//            $res[] = Db::name('store_member')->where(['id' => $this->wx_user_id])->setDec('account_money', $data['num']);
            $res['orderid'] = Db::name('store_order_c2c')->insertGetId($arr);
        } elseif ($data['type'] == 1) {
            $res['orderid'] = Db::name('store_order_c2c')->insertGetId($arr);
            if ($orderId > 0) {
                $res[] = Db::name('StoreOrderC2c')->where(['id' => $orderId])->update(['status' => 2, 'other_order_id' => $res['orderid']]);
                //买入中心的 订单
                $sell_orderInfo = Db::name('store_order_c2c')->where(['id' => $orderId])->find();
                $relation_order_c2c = [
                    'fromid' => $this->wx_user_id, //买的人id
                    'toid' => $sell_orderInfo['mid'], //买出人
                    'status' => 2,
                    'create_at' => get_time(),
                    'orderid' => $res['orderid']
                ];
                $seller_phone = Db::name('store_member')->where(['id' => $sell_orderInfo['mid']])->value('phone');
                $res['send_messsage'] = sendMobileMessage($seller_phone, ['code' => $sell_orderInfo['order_no']], '499820');
                $res['order_update_status'] = Db::name('store_order_c2c')->where(['id' => $res['orderid']])->update(['status' => 2]);
                $res['insert_c2c_relation'] = DataService::save('StoreC2cRelation', $relation_order_c2c);
            }
        }
        if (check_arr($res)) {
            Db::commit();
            if ($orderId > 0) {
                $this->success('操作成功', ['orderid' => $res['orderid']]);
            }
            $this->success('操作成功');
        } else {
            Db::rollback();
            $this->error('操作失败');
        }
    }

    //获取订单信息
    public function getC2cOrderDetail()
    {
        $orderId = input('post.orderId');
        !$orderId && $this->error('订单ID不能为空');
        //20001 没有撮合  20002  撮合了  20003 已经完成
        $orderInfo = Db::name('store_member a')
            ->field('a.id,a.phone,a.account_money,b.num,b.real_price,b.order_no,b.create_at,b.status')
            ->join("store_order_c2c b", "a.id = b.mid")
            ->where(['b.id' => $orderId])
            ->find();
        $this->success('', $orderInfo);
    }


    //待打款页面
    public function getC2cOrderWaitDetail()
    {
        $orderId = input('post.orderId');
        !$orderId && $this->error('订单ID不能为空');
        $orderInfo['order_info'] = Db::name('store_member a')
            ->field('a.id,a.phone,a.account_money,b.num,b.real_price,b.order_no,b.create_at,b.end_time,b.mid,b.type,b.id as orderid,b.interval_id,b.status')
            ->join("store_order_c2c b", "a.id = b.mid")
            ->where(['b.id' => $orderId])
            ->find();
        $orderInfo['order_info']['interval_info'] = Db::name('store_order_interval')->where(['id' => $orderInfo['order_info']['interval_id']])->value('title');
        $info = Db::name('store_member a')
            ->field('a.id,a.phone,a.account_money,b.num,b.real_price,b.order_no,b.create_at,b.mid,b.type,b.id as orderid,b.dakuan_image')
            ->join("store_order_c2c b", "a.id = b.mid")
            ->where(['b.other_order_id' => $orderId])
            ->find();
        $orderInfo['order_info']['phone'] = $info['phone'];
        $orderInfo['order_info']['dakuan_image'] = $info['dakuan_image'];
        $orderInfo['payment_zfb'] = Db::name('store_member_payment')->where(['uid' => $info['mid'], 'type' => 2])->find();
        $orderInfo['payment_wexin'] = Db::name('store_member_payment')->where(['uid' => $info['mid'], 'type' => 1])->find();
        $orderInfo['payment_bank'] = Db::name('store_member_bank')->where(['uid' => $info['mid']])->find();
        $orders = Db::name('store_order_c2c')->where(['id' => $orderId])->find();
        if ($orders['type'] == 1) {
            //买入订单
            $daon = Db::name('store_c2c_relation')->where(['orderid' => $orderId])->find();
        } elseif ($orders['type'] == 2) {
            //卖出订单 的交易时间
            $daon = Db::name('store_c2c_relation')->where(['orderid' => $orders['other_order_id']])->find();
        }
        $orderInfo['countdown'] = $daon['create_at'] + 3600 * 24 - get_time();
//        if($orderInfo['countdown'] <=0){
//            $this->error();
//        }
//        if($orderInfo['order_info']['type'] == 2){
//            $orderInfo['countdown'] = 0;
//        }else{
//
//        }

        $this->success('', $orderInfo);
    }

    //买家确认付款
    public function confrimFukuan()
    {

        $image = input('post.image');
        $orderid = input('post.orderId');
        !$image && $this->error('上传打款截图不能为空');
        !$orderid && $this->error('订单号不能为空');

        Db::startTrans();
        $orderInfo = Db::name('store_order_c2c')->where(['id' => $orderid])->find();
        if ($orderInfo['status'] == 3 || $orderInfo['status'] == 10) {
            $this->error('交易超时或者卖家已经确认收款,订单已完成');
        }
        $sell_order_id = Db::name('store_order_c2c')->where(['id' => $orderid])->value('other_order_id');
        $res[] = Db::name('store_order_c2c')->where(['id' => $orderid])->update(['dakuan_image' => $image, 'status' => 4]) !== FALSE; //卖家
        $res[] = Db::name('store_order_c2c')->where(['id' => $sell_order_id])->update(['dakuan_image' => $image, 'status' => 4]) !== FALSE;//卖家
        $res[] = Db::name('store_c2c_relation')->where(['orderid' => $orderid])->update(['status' => 4, 'create_at' => get_time()]) !== FALSE;
        if (check_arr($res)) {
            Db::commit();
            $this->success('确认付款成功');
        } else {
            Db::rollback();
            $this->error('确认付款失败');
        }
    }

    //卖家确认收款
    public function confrimShouKuan()
    {
        $orderid = input('post.orderId');
        !$orderid && $this->error('订单号不能为空');
        $orderInfo = Db::name('store_member a')
            ->join('store_order_c2c b', "a.id = b.mid")
            ->where(['b.id' => $orderid])->find(); //卖家订单
        if ($orderInfo['status'] == 10) $this->error('订单已经超时');
        !$orderInfo['other_order_id'] && $this->error('收款失败');
        $infoResult = Db::name('store_order_c2c a')
            ->field('a.id as orderid,a.num,a.order_no,a.mid,b.*')
            ->join('store_member b', "a.mid =b.id")
            ->where(['a.id' => $orderInfo['other_order_id']])
            ->find();

        if ($orderInfo['status'] == 3 || $orderInfo['status'] == 10) {
            $this->error('交易已完成');
        }

        if (empty($orderInfo['dakuan_image'])) $this->error('买家还没有确认付款');

        Db::startTrans();
        $res[] = Db::name('store_order_c2c')->where(['id' => $orderid])->update(['status' => 3, 'end_time' => get_time()]);
        $res[] = Db::name('store_order_c2c')->where(['id' => $orderInfo['other_order_id']])->update(['status' => 3, 'end_time' => get_time()]);
        $res[] = mlog($infoResult['mid'], 'account_money', $infoResult['num'], '购买PDR' . $infoResult['num'] . '个', 'buy_pdr', $infoResult['id']);
        //交易挖矿收益
        if ($orderInfo['num'] * sysconf('seller_mining') / 100 > 0) {
            $res[] = mlog($orderInfo['mid'], 'account_money', $orderInfo['num'] * sysconf('seller_mining') / 100, '交易挖矿收益' . $orderInfo['num'] / 100 * sysconf('seller_mining') . '个', 'pay_mining', $orderInfo['id']);
        }

        if ($infoResult['num'] * sysconf('buy_mining') / 100) {
            $res[] = mlog($infoResult['mid'], 'account_money', $infoResult['num'] * sysconf('buy_mining') / 100, '交易挖矿收益' . $infoResult['num'] * sysconf('buy_mining') / 100 . '个', 'pay_mining', $infoResult['id']);
        }

        $res[] = Db::name('store_c2c_relation')->where(['orderid' => $orderInfo['other_order_id']])->update(['status' => 3]) !== FALSE;

        if (check_arr($res)) {
            sendMobileMessage($infoResult['phone'], ['useranme' => $orderInfo['nickname'], 'orderno' => $infoResult['order_no'], 'paynum' => $infoResult['num']], '499821');
            Db::commit();
            $this->success('收款成功');
        } else {
            Db::rollback();
            $this->error('收款失败');
        }

    }


    public function getCarryC2cOrder()
    {
        $orderid = input('post.orderid');
        !$orderid && $this->error('订单号不能为空');
        $infoResult = Db::name('store_order_c2c a')
            ->field('a.id as orderid,a.num,a.order_no,b.*')
            ->join('store_member b', "a.mid =b.id")
            ->where(['a.id' => $orderid])
            ->find();
        $this->success('', $infoResult);
    }

    //取消订单
    public function cancelC2cOrder()
    {
        $orderId = input('param.orderId');
        !$orderId && $this->error('订单ID不能为空');
        Db::startTrans();
        $orderInfo = Db::name('store_order_c2c')->where(['id' => $orderId])->find();
        $orderInfo['status'] != 1 && $this->error('当前订单不能取消,尝试刷新网页');

        if ($orderInfo['type'] == 1) {
            //TODO 买入
        } elseif ($orderInfo['type'] == 2) {
            //
            $res[] = mlog($orderInfo['mid'], 'account_money', $orderInfo['num'], '取消订单返回PDR' . $orderInfo['num'], 'cancel_C2c_order', $orderId);
        }
        $res[] = Db::name('store_order_c2c')->where(['id' => $orderId])->update(['status' => 5]);
        if (check_arr($res)) {
            Db::commit();
            $this->success('取消成功');
        } else {
            Db::rollback();
            $this->error('取消失败');
        }

    }

    //投诉处理
    public function complaint()
    {
        $orderId = input('post.orderId');
        $imagePath = input('post.imagePath');
        $content = input('post.content');
        if (empty($imagePath))
            $this->error('请上传投诉截图');
        if (empty($content))
            $this->error('请填写投诉内容');
        $relationOrderInfo = \getC2cOrderPayTime($orderId);
        $orderinfo = Db::name('store_order_c2c')->where(['id' => $orderId])->find();

        if (!$orderinfo)
            $this->error('订单不存在');

        if ($orderinfo['status'] == 6)
            $this->error('请勿重复操作');
//        //查看是否倒计时结束
        $endtime = strtotime($relationOrderInfo['create_at']) + self::TSDJS;
        if ($endtime > time())
            $this->error('投诉时间还未到,请耐心等待');

//        //在有效时间内投诉有效
//        $jztime = strtotime($orderinfo['create_at']) + self::TSJZ;
//        if ($jztime < time()) {
//            $this->error('订单交易15分钟内不能进行投诉');
//        }
        $ts_Arr = [
            'uid' => $orderinfo['mid'],
            'order' => $orderinfo['id'],//投诉订单ID
            'buid' => Db::name('store_order_c2c')->where(['id' => $orderinfo['other_order_id']])->value('mid'),
            'border' => $orderinfo['other_order_id'], //被投诉订单ID
            'caeate_at' => time(),
            'status' => 0, //0未处理  1已处理
            'image_path' => $imagePath,
            'content' => $content,
        ];
        Db::startTrans();
        if ($orderinfo['type'] == 1) {//转入
            $ts_Arr['type'] = 1;
        } else { //转出type == 2
            $ts_Arr['type'] = 2;
        }
        $res[] = Db::name('store_order_c2c')->where(['id' => $orderId])->update(['status' => 6]);//投诉改变订单状态(投诉订单)
        $res[] = Db::name('store_order_c2c')->where(['id' => $orderinfo['other_order_id']])->update(['status' => 6]);//投诉改变订单状态(被投诉订单)
        $res[] = Db::name('store_order_c2c_ts')->insert($ts_Arr);
        if (check_arr($res)) {
            Db::commit();
            $this->success('投诉成功');
        } else {
            Db::rollback();
            $this->error('投诉失败');
        }
    }

    //获取pdr记录
    public function getPdrRecord()
    {
        $result = Db::name('bags_log')
            ->where(['uid' => $this->wx_user_id])
            ->where('extends', 'in', 'sell_pdr,buy_pdr,reduce_power,increase_power,seller_mining,buy_mining,time_out_transaction_money_return,time_out_transaction_money_arrival,cancel_dig_account,increase_pdr_collar,merchant_pdr_shou,merchant_pdr_shou_reduce')
            ->page($this->page, $this->max_page_num)
            ->order('id desc')
            ->select();
        foreach ($result as &$v) {
            $v['money'] = reserve_num($v['money']);
            $v['extends'] = get_extends_txt($v['extends']);
            $v['create_time'] = format_time($v['create_time']);
            $v['after_money'] = reserve_num($v['money'] + $v['before']);
        }
        $this->success($result);
    }

    //获取今日收益
    public function getTodayBonus()
    {
        $result = Db::name('bags_log')
            ->where(['uid' => $this->wx_user_id])
            ->where('extends', 'in', 'static_bonus,team_bonus_money,share_dig,lettery,pay_mining')
            ->whereTime('create_time', 'today')
            ->page($this->page, $this->max_page_num)
            ->select();
        foreach ($result as &$v) {
            $v['money'] = reserve_num($v['money']);
            $v['extends'] = get_extends_txt($v['extends']);
            $v['create_time'] = format_time($v['create_time']);
            $v['after_money'] = reserve_num($v['money'] + $v['before']);
        }
        $this->success($result);
    }


    //获取今日收益
    public function getHashDayBonus()
    {
        $orderId = input('post.orderId');
        !$orderId && $this->error('订单ID不能为空');
        $result = Db::name('bags_log')
            ->where(['uid' => $this->wx_user_id, 'orderId' => $orderId])
            ->where('extends', 'in', 'static_bonus')
            ->page($this->page, $this->max_page_num)
            ->select();
        foreach ($result as &$v) {
            $v['extends'] = get_extends_txt($v['extends']);
        }
        $this->success($result);
    }

    /***************************************C2C结束********************************************************/

    /***************************************交易相关*******************************************************/

    //用户升级列表
    public function upgradeUser()
    {
        $member_level = $this->wx_user['member_level'] > 2 ? $this->wx_user['member_level'] + 1 : 3;
        $upgradeInfo = Db::name('sys_level')->where(['id' => $member_level])->find();
        $this->success($upgradeInfo);
    }

    //升级用户1
    public function upgradeUserLevel()
    {
        $flag = true;
        if ($flag) {
            if ($this->wx_user['member_level'] == 12) {
                $this->error('不满足条件,升级失败');
            }
            $userLevel = Db::name('sys_level')->where(['id' => $this->wx_user['member_level'] + 1])->find();
            //团队粉丝
            $team_fans = Db::query("SELECT count(*) as sub_person_count  FROM `store_member` WHERE FIND_IN_SET($this->wx_user_id,all_leader)")[0]['sub_person_count'];
            //直接分享粉丝
            $direct_share_fans = Db::name('store_member')->where(['first_leader' => $this->wx_user_id])->count();
            $drive = Db::name('store_member')->where(['first_leader' => $this->wx_user_id])->where('member_level', ">=", 2)->count();
//            $shiming = Db::name('store_member')->where(['first_leader' => $this->wx_user_id])->select();
//            foreach ($shiming as $k => $v) {
//                $shiming[$k]['count'] = Db::name('store_member_idcard')->where(['status' => 1, 'uid' => $v['id']])->count();
//                //直推实名
//            }
//            $mining_total = array_sum(array_column($shiming, 'count'));
            if ($drive >= $userLevel['share'] && $team_fans >= $userLevel['fans'] && $this->wx_user['hashrate'] >= $userLevel['force']) {
                $upgradeRecordFlag = Db::name('store_member_upgrade_record')->where(['uid' => $this->wx_user_id, 'upgradeLevel' => $this->wx_user['member_level'] + 1])->find();
                Db::startTrans();
                if ($upgradeRecordFlag) {
                    $res[] = Db::name('store_member')->where(['id' => $this->wx_user_id])->setInc('member_level');
                } else {
                    $upgradeRecord = [
                        'uid' => $this->wx_user_id,
                        'addtime' => get_time(),
                        'upgradeLevel' => $this->wx_user['member_level'] + 1
                    ];
                    $res[] = Db::name('store_member_upgrade_record')->insertGetId($upgradeRecord);
                    $res[] = Db::name('store_member')->where(['id' => $this->wx_user_id])->setInc('member_level');
                    if ($this->wx_user['account_money'] < $userLevel['num']) $this->error('账户PDR金额不足');
                    $res[] = mlog($this->wx_user_id, 'account_money', -$userLevel['num'], "升级{$userLevel['title']},消耗PDR{$userLevel['num']}", 'upgrade_consum');
                }
                if (check_arr($res)) {
                    Db::commit();
                    $this->success('升级成功');
                } else {
                    Db::rollback();
                    $this->error('升级失败');
                }

            } else {
                $this->error('不满足条件,升级失败');
//                $this->error("不满足条件,升级失败{$drive}|{$userLevel['share']}+{$team_fans}|{$userLevel['fans']}+{$this->wx_user['hashrate']}|{$userLevel['force']}");
            }
        } else {
            $this->error('不满足条件,升级失败');
        }
    }


    public function getUserUpgradeTips()
    {
        $result = Db::name('store_member_upgrade_record')->where(['uid' => $this->wx_user_id, 'upgradeLevel' => $this->wx_user['member_level'] + 1])->find();
        if (!$result) {
            $levelInfo = Db::name('sys_level')->where(['id' => $this->wx_user['member_level'] + 1])->find();
            $this->success('本次升级需要消耗PDR' . $levelInfo['num'] . '个');
        } else {
            $this->success('本次升级不需要消耗PDR');
        }
    }

    //获取交易记录
    public function getBagLogs()
    {
        $data = input('post.');
        $validate = Validate::make([
            'extends' => 'require',
        ], [
            'extends.require' => '数据类型不能为空,请填写|static_bonus=静态挖矿|team_bonus_money=团队收益|',
        ]);
        $validate->check($data) || $this->error($validate->getError());
        $data = Db::name('bags_log')->where(['uid' => $this->wx_user_id, 'extends' => $data['extends']])->select();
        $this->success($data);
    }


    //算力交易
    public function transAction()
    {
        $data = input('post.');
        $validate = Validate::make([
            'type' => 'require',
            'num' => 'number',
            'paypassword' => 'require'
        ], [
            'type.require' => '1--转入 2 --卖出',
            'num.require' => '转入数量格式不正确',
            'paypassword.require' => '请填写交易密码',
        ]);
        $validate->check($data) || $this->error($validate->getError());
        $data['num'] % 10 != 0 && $this->error('操作数量必须是10的倍数');
        if (md5($data['paypassword']) != $this->wx_user['paypassword']) {
            $this->error('交易密码不正确');
        }
        Db::startTrans();
        $arr = [
            'type' => $data['type'],
            'mid' => $this->wx_user_id,
            'order_no' => $this->wx_user_id . rand(100000, 999999) . time(),
            'real_price' => $data['num'],
        ];
        //转入
        //获取当前用户上级的 推广了多少人
        $buyTotal = Db::name('store_order')->where(['mid' => $this->wx_user_id, 'status' => 1])->sum('real_price'); //当前用户累计购买的
        if ($data['type'] == 1) {
            if ($this->wx_user['member_level'] <= 2) {
                //TODO  星级以下
                $data['num'] + $this->wx_user['hashrate'] > 100000 && $this->error('星级以下算力挖矿最多持有100000');
            } else {
                //  一星以上
                $memberLevelInfo = Db::name('sys_level')->where(['id' => $this->wx_user['member_level']])->find();
                $data['num'] + $this->wx_user['hashrate'] > $memberLevelInfo['mining'] && $this->error("{$memberLevelInfo['title']}以下算力挖矿最多持有{$memberLevelInfo['mining']}");
            }
            $data['num'] > $this->wx_user['account_money'] && $this->error('PDR账户金额不足');
            $content = "增加算力挖矿{$data['num']},减少PDR{$data['num']}";
            $res[] = Db::name('store_member')->where(['id' => $this->wx_user_id])->setInc('hashrate', $data['num']);
            $res[] = mlog($this->wx_user_id, 'account_money', -$data['num'], $content, 'reduce_power');  //增加算力挖矿,而减少PDR
            $flagSpread = Db::name('es_spread_record')->where(['uid' => $this->wx_user_id, 'toid' => $this->wx_user['first_leader']])->find(); //是否增加过算力
            if ($buyTotal + $data['num'] >= 100 || $data['num'] >= 100) {
                if ($this->wx_user['member_level'] == 1) {
                    $res[] = Db::name("store_member")->where(['id' => $this->wx_user_id])->update(['member_level' => 2]) !== FALSE;
                }

            }
            if (!$flagSpread) {
                if ($buyTotal >= 100 || $data['num'] >= 100) {
                    $first_leader_count = Db::name('es_spread_record')->where(['toid' => $this->wx_user['first_leader']])->count();  //获取当前用户上级推广几个人。

                    if ($this->wx_user['first_leader']) {
                        if ($first_leader_count == 0) {
                            $first_leader_count = 1;
                        }
                        if ($first_leader_count > 10) {
                            $give_hashrate = 10;
                        } else {
                            $give_hashrate = Db::name("sys_hashrate")->where(['id' => $first_leader_count])->value('hashrate'); //Zensong的算力
                        }

                        $content = "第{$first_leader_count}正式用户,推广{$this->wx_user['nickname']},获取到分享算力:{$give_hashrate}";
                        $res[] = mlog($this->wx_user['first_leader'], 'mining', $give_hashrate, $content, 'share_dig_spread');
                        $res[] = Db::name('es_spread_record')->insert(['uid' => $this->wx_user_id, 'toid' => $this->wx_user['first_leader']]);
                    }
                }
            }

        } elseif ($data['type'] == 2) {
            $hash_switch = sysconf('is_of_hashrate');
            if ($hash_switch == -1 || !$hash_switch) {
                $this->error('算力挖矿暂时不能转出');
            }

            if ($this->wx_user['member_level'] <= 2) {
                if ($buyTotal - $data['num'] < 100) {
                    $res[] = Db::name("store_member")->where(['id' => $this->wx_user_id])->update(['member_level' => 1]) !== FALSE;
                }
            } else {
                $force = Db::name('sys_level')->where('id', $this->wx_user['member_level'])->value('force');
                if ($buyTotal - $data['num'] < $force) {
                    $res[] = Db::name("store_member")->where(['id' => $this->wx_user_id])->update(['member_level' => 2]) !== FALSE;
                }
            }
            if ($buyOrder = Db::name('store_order')->where(['mid' => $this->wx_user_id, 'id' => $data['id']])->find()) {
                if ($buyOrder['status'] != 1) {
                    $this->error('不能重复操作');
                }

            }

            $content = "增加PDR{$data['num']},减少算力挖矿{$data['num']}";
            $res[] = mlog($this->wx_user_id, 'account_money', $data['num'], $content, 'increase_power');  //减少算力挖矿,而增加PDR
            $res[] = Db::name('store_member')->where(['id' => $this->wx_user_id])->setDec('hashrate', $data['num']);
            //TODO 卖出操作
            if (isset($data['id'])) {
                $arr['id'] = $data['id'];
                $arr['status'] = 2;
                unset($arr['order_no']);
            } else {
                $this->error('缺少参数id');
            }
        }
        $res[] = DataService::save('StoreOrder', $arr);
        if (check_arr($res)) {
            Db::commit();
            $this->success('操作成功');
        } else {
            Db::rollback();
            $this->error('操作失败');
        }
    }


//    //获取算力交易列表
    public function getTransOrderRecord()
    {
        $data = Db::name('store_order a')
            ->field('a.*')
            ->join('store_member b', "a.mid = b.id")
            ->where(['a.mid' => $this->wx_user_id])
            ->page($this->page, $this->max_page_num)
            ->order('a.create_at desc')
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['real_price'] = reserve_num($v['real_price']);
            $data[$k]['bonus_total'] = Db::name("bags_log")->where(['orderId' => $v['id'], 'uid' => $this->wx_user_id])->where('extends', 'in', 'static_bonus')->sum('money'); //获取当前订单的十天内的算力挖矿收益统计
            $data[$k]['create_at'] = str_replace(date('Y') . '-', '', $v['create_at']);
        }
        $this->success('', $data);
    }

    //收益记录
    public function getTransRecord()
    {
        $data = Db::name('bags_log')->where(['uid' => $this->wx_user_id])->where('extends', 'in', 'static_bonus,team_bonus_money,share_dig,lettery')->page($this->page, $this->max_page_num)->order('create_time desc')->select();
        foreach ($data as &$v) {
            $v['money'] = reserve_num($v['money']);
            $v['extends'] = get_extends_txt($v['extends']);
            $v['create_time'] = format_time($v['create_time']);
            $v['after_money'] = reserve_num($v['money'] + $v['before']);
        }
        $this->success($data);
    }

    //算力收益
    public function getPowerList()
    {
        $data = Db::name('bags_log')->where(['uid' => $this->wx_user_id])->where('extends', 'in', 'static_bonus,team_bonus_money,share_dig')->page($this->page, $this->max_page_num)->select();
        $this->success($data);
    }

    public function getPowerDetail()
    {
        $res = [];
        $res['personal_total_bonus'] = Db::name('bags_log')->where(['uid' => $this->wx_user_id])->where('extends', 'in', 'static_bonus,team_bonus_money')->sum('money');
        $res['total_bonus'] = Db::name('store_order')->where(['type' => 1])->sum('real_price') + sysconf('pdr_web') . 'PDR/D';
        $res['share_bonus'] = $this->wx_user['mining'];
        $res['total_share_bonus'] = Db::name('bags_log')->where(['uid' => $this->wx_user_id])->where('extends', 'in', 'share_dig')->sum('money');;
        $res['power_bonus'] = $this->wx_user['hashrate'];
        return $this->success($res);
    }

    //是否可以收矿
    public function getFLagDigMine()
    {
        $recent_bonus_log = Db::name("bags_log")->where(['extends' => 'share_dig', 'uid' => $this->wx_user_id])->order('create_time desc')->find();
        if (!empty($recent_bonus_log)) {
            $one_day_after = $recent_bonus_log['create_time'] + 86400; //最近时间 一天后
            if ($one_day_after - get_time() > 0) {
                $remain_time = $one_day_after - get_time();
                $this->success(['recent_bonus_log' => $recent_bonus_log, 'remain_time' => $remain_time]);
            }
        }
        return $this->error('首次直接可以收矿');
    }
    /*****************************************交易相关结束*****************************************************/
    //签到
    public function getCheckIn()
    {
        try {
            $this->commonService->setUserID($this->wx_user_id)->checkIn();
            $this->success('签到成功');
        } catch (\member\CommonException $e) {
            $this->error($e->getMessage());
        }
    }

    //静态挖矿
    public function getStaticMine()
    {
        try {
            $this->commonService->setUserID($this->wx_user_id)->stillMining();
        } catch (\member\CommonException $e) {
            $this->error($e->getMessage());
        }
    }

    //发送验证码
    public function sendMobileMessage()
    {
        $code = rand(10000, 99999);
        $data = input('param.');
        if (empty($data['phone'])) {
            $data['phone'] = Db::name('store_member')->where(['id' => $this->wx_user_id])->value('phone');
            !$data['phone'] && $this->error('手机号不存在,请先去绑定手机');
            $this->setSmsCode('code', $code, $data['phone']);
            $result = sendMobileMessage($data['phone'], ['code' => $code], '499532');
            $this->success($result);
        } else {
            $this->setSmsCode('code', $code, $data['phone']);
            $result = sendMobileMessage($data['phone'], ['code' => $code], '499532');
            $this->success($result);
        }
    }


    //分享算力挖矿
    public function shareDig()
    {
        try {
            $this->commonService->setUserID($this->wx_user_id)->BonusShareDig();
            $this->success('收取成功');
        } catch (\member\CommonException $e) {
            $this->error($e->getMessage());
        }
    }

    /******************************抽奖开始**********************************/
    //获取抽奖列表
    public function getLetteryList()
    {
        $list = Db::name('sys_lettery')->select();
        $list = shuffle_assoc($list);
        $this->success(['list' => $list, 'consum_pdr' => sysconf('lottery_num')]);
    }

    //开始抽奖    --暂不使用
    public function goLettery()
    {
        $list = Db::name('sys_lettery')->select();
        $lottery = new \Smallsha\Classes\Lottery($list, 'sort');
        $result = $lottery->getDataRand();
        $chou_lottery = sysconf('lottery_num');
        if ($this->wx_user['account_money'] < $chou_lottery) {
            $this->error('PDR余额不足');
        }
        $letteryCount = Db::name('bags_log')->where(['uid' => $this->wx_user_id, 'extends' => 'chou_lottery'])->whereTime('create_time', 'd')->count('id');
        $letteryCount > 10 && $this->error('抽奖次数每天不能大于10次');
        Db::startTrans();
        $res[] = mlog($this->wx_user_id, 'account_money', -$chou_lottery, "抽奖消耗PDR:$chou_lottery", 'chou_lottery');
        $winInfo = Db::name('sys_lettery')->where(['id' => $result['win_key']])->find(); //中奖信息
        $content = '中奖获取PDRS:' . $winInfo['num'];
        if ($winInfo['num'] > 0) {
            $res[] = mlog($this->wx_user_id, 'pdrs', $winInfo['num'], $content, 'lettery');
        }
        if (check_arr($res)) {
            Db::commit();
            if ($winInfo['num'] > 0) {
                $this->success("恭喜您获得" . $winInfo['num'] . "PDRS", $winInfo['num']);
            } else {
                $this->error('谢谢参与', $winInfo['num']);
            }

        } else {
            Db::rollback();
            $this->error('抽奖失败');
        }
    }

    //现用抽奖
    public function addLottery()
    {
        $num = input('param.num', 0);
        $chou_lottery = sysconf('lottery_num');
        if ($this->wx_user['account_money'] < $chou_lottery) {
            $this->error('PDR余额不足');
        }

        if ($num > 0) {
            Db::startTrans();
            $res[] = mlog($this->wx_user_id, 'account_money', -$chou_lottery, "抽奖消耗PDR:$chou_lottery", 'chou_lottery');
            $content = '中奖获取PDRS:' . $num . '元';
            $res[] = mlog($this->wx_user_id, 'pdrs', $num, $content, 'lettery');
            if (check_arr($res)) {
                Db::commit();
                $this->success('抽奖成功');
            } else {
                Db::rollback();
                $this->error('抽奖失败');
            }
        } else {
            $this->success('抽奖成功');
        }

    }

    //获取中奖纪录
    public function getLetterRecord()
    {
        $result = Db::name('bags_log')
            ->where(['uid' => $this->wx_user_id, 'extends' => 'lettery'])
            ->page($this->page, $this->max_page_num)
            ->order('create_time desc')
            ->select();
        foreach ($result as &$v) {
            $v['create_time'] = format_time($v['create_time']);
            $v['money'] = '获得' . ($v['money'] * 1) . 'PDRS';
        }
        $this->success($result);
    }
    /******************************抽奖结束**********************************/
    //获取分享推广统计
    public function getPromotionList()
    {
        $result = Db::name('bags_log')
            ->where(['uid' => $this->wx_user_id, 'extends' => 'share_dig_spread'])
            ->page($this->page, $this->max_page_num)
            ->order('create_time desc')
            ->select();
        foreach ($result as &$v) {
            $v['money'] = reserve_num($v['money']);
            $v['extends'] = get_extends_txt($v['extends']);
            $v['create_time'] = format_time($v['create_time']);
            $v['after_money'] = reserve_num($v['money'] + $v['before']);
        }
        $this->success($result);
    }

    /*****************************增加扫码转账功能*********************************/

    public function generateMerchantQrcode()
    {
        $flagMerchat = Db::table('sys_merchat')->where(['uid' => $this->wx_user_id])->find();
        if ($flagMerchat) {
            if ($flagMerchat['status'] == 0) {
                $this->success('审核中', '', 2);
            } elseif ($flagMerchat['status'] == 1) {
                $imgUrl = '/static/upload/' . md5($this->wx_user['id'] . $this->wx_user['phone'] . 'merchat') . '.png';
                $file = ROOT_PATH . $imgUrl;
                $content = '{"uid":' . $this->wx_user_id . '}';
                makeQrcode($content, $file);
                $this->success('成功', ['qrcodeUrl' => 'http://' . $_SERVER['HTTP_HOST'] . $imgUrl . '?time=' . get_time()]);
            }
        } else {
            $this->error('您还不是商户呢', '', -1);
        }
    }

    public function getMerchatInfo()
    {
        $data = input('post.');
        $validate = Validate::make([
            'merchatId' => 'require',
        ], [
            'merchatId.require' => '商户id不能为空',
        ]);
        $validate->check($data) || $this->error($validate->getError());
        $merchatInfo = Db::name('sys_merchat a')
            ->join('store_member b', "a.uid = b.id")
            ->where(['a.uid' => $data['merchatId'], 'a.status' => 1])
            ->find();
        if (!empty($merchatInfo)) {
            $this->success($merchatInfo);
        } else {
            $this->error('商户不存在', '', -4001);
        }
    }

    public function applyMerchant()
    {
        $data = input('post.');
        $validate = Validate::make([
            'merchatname' => 'require',
        ], [
            'merchatname.require' => '商户名称不能为空',
        ]);
        $validate->check($data) || $this->error($validate->getError());
        $flagMerchat = Db::name('sys_merchat')->where(['title' => $data['merchatname']])->find();
        if ($flagMerchat) {
            $this->error('商户名称已经被占用');
        } else {
            $arr['add_at'] = get_time();
            $arr['uid'] = $this->wx_user_id;
            $arr['title'] = $data['merchatname'];
            if (DataService::other_save('SysMerchat', $arr, ['uid' => $this->wx_user_id])) {
                $this->success('申请成功');
            } else {
                $this->error('网络故障,申请商户失败');
            }
        }
    }

    //转账给商户
    public function transferMerchat()
    {
        $data = input('post.');
        $validate = Validate::make([
            'merchatname' => 'require',
            'num' => 'require',
            'paypassword' => 'require'
        ], [
            'merchatname.require' => 'merchatname不能为空',
            'num.require' => 'num不能为空',
            'paypassword.require' => 'paypassword不能为空',
        ]);
        $validate->check($data) || $this->error($validate->getError());
        $merchatInfo = Db::name('sys_merchat')->where(['title' => $data['merchatname']])->find();
        if ($merchatInfo) {
            if ($merchatInfo['status'] == 1) {
                $this->wx_user['paypassword'] != md5($data['paypassword']) && $this->error('支付密码不正确');
                $this->wx_user['account_money'] < $data['num'] && $this->error('PDR余额不足');
                $pdr_money = $data['num'] * sysconf('merchant_pdr_shou') / 100;
                $share_mining = $data['num'] * sysconf('merchant_mining_shou') / 100;

                Db::startTrans();
                //处理打款方
                $res[] = mlog($this->wx_user_id, 'account_money', -$data['num'], "给商户({$merchatInfo['title']}),转账PDR减少PDR{$data['num']}个", 'merchant_pdr_shou_reduce');
                $res[] = mlog($this->wx_user_id, 'integral', $data['num'], "给商户({$merchatInfo['title']}),转账增加积分{$data['num']}个", 'merchant_mining_shou');
                //处理收款方
                $res[] = mlog($merchatInfo['uid'], 'account_money', $pdr_money, "商户({$merchatInfo['title']}),收到" . $this->wx_user['nickname'] . "转账PDR{$pdr_money}个", 'merchant_pdr_shou', '', '', $this->wx_user_id);
                $res[] = mlog($merchatInfo['uid'], 'integral', $share_mining, "商户({$merchatInfo['title']}),收到" . $this->wx_user['nickname'] . "转账积分增加{$share_mining}个", 'merchant_mining_shou');
                if (check_arr($res)) {
                    Db::commit();
                    $this->success('转账成功');
                } else {
                    Db::rollback();
                    $this->error('网络故障,转账失败');
                }
            } else {
                $this->error('当前账户还没有开通商户功能');
            }
        } else {
            $this->error('商户不存在');
        }

    }


    //转账记录
    public function transferList()
    {
        $data = Db::name('bags_log a')
            ->join('store_member b', 'a.fromid = b.id')
            ->where(['uid' => $this->wx_user_id, 'extends' => 'merchant_pdr_shou'])
            ->page($this->page, $this->max_page_num)
            ->order('a.create_time desc')
            ->select();
        if (empty($data)) {
            $this->error('暂无数据');
        }
        return $this->success($data);
    }

    //获取积分记录
    public function getIntegralRecord()
    {
        //获取pdr记录
        $result = Db::name('bags_log')
            ->where(['uid' => $this->wx_user_id])
            ->where('extends', 'in', 'merchant_mining_shou,merchant_mining_reduce')
            ->page($this->page, $this->max_page_num)
            ->order('id desc')
            ->select();
        foreach ($result as &$v) {
            $v['money'] = reserve_num($v['money']);
            $v['extends'] = get_extends_txt($v['extends']);
            $v['create_time'] = format_time($v['create_time']);
            $v['after_money'] = reserve_num($v['money'] + $v['before']);
        }
        $this->success($result);
    }

    //判断当天是否有积分可以领取
    public function getTodayReceiveIntegral()
    {
        $flag = $this->commonService->lookIntegralRecord($this->wx_user_id);
        if ($flag) {
            $this->success('有红包可以领', $flag);
        } else {
            $this->error('没有红包领');
        }
    }

    //领取红包
    public function receiveIntegralTurnPdr()
    {
        $flag = $this->commonService->lookIntegralRecord($this->wx_user_id);
        if ($this->wx_user['integral'] < $flag['money']) {
            $this->error('您的积分余额不足');
        }
        if ($flag) {
            Db::startTrans();

            $res[] = true;
            $res[] = mlog($this->wx_user_id, 'integral', -$flag['money'], '领取PDR奖励,减少积分' . $flag['money'], 'merchant_mining_reduce');
            $res[] = mlog($this->wx_user_id, 'account_money', $flag['money'], '通过积分,领取PDR奖励' . $flag['money'], 'increase_pdr_collar');
            $res[] = Db::name('es_integral_bonus')->where(['id' => $flag['id']])->update(['status' => 1]);
            if (check_arr($res)) {
                Db::commit();
                $this->success('领取成功');
            } else {
                Db::rollback();
                $this->error('领取失败');
            }
        } else {
            $this->error('没有红包领');
        }
    }


    //兑换scale
    public function exchangePdrToPdrs()
    {
        $data = input('post.');
        $validate = Validate::make([
            'num' => 'require',
            'paypassword' => 'require'
        ], [
            'num.require' => 'num不能为空',
            'paypassword.require' => 'paypassword不能为空',
        ]);
        $validate->check($data) || $this->error($validate->getError());
        $pdrs = $data['num'] / sysconf('exchange_scale');
        $countPdrRecords = Db::table('bags_log')->where(['uid' => $this->wx_user_id, 'extends' => 'exchanges_pdr_recude'])->sum('money');
        if ($countPdrRecords > 10000) $this->error('兑换数量不能超过10000');
        if ($data['num'] < 0) $this->error('操作数量不正确');
        if ($this->wx_user['account_money'] < $pdrs) $this->error('pdr余额不足');
        if ($pdrs > sysconf('pdrs_surplus') || strtotime(sysconf('pdrs_exchange')) - get_time() < 0) $this->error('兑换尚未开启');
        if (md5($data['paypassword']) != $this->wx_user['paypassword']) $this->error('支付密码不正确');
        Db::startTrans();
        $res = [];
        $res[] = mlog($this->wx_user_id, 'account_money', -$pdrs, "兑换pdrs,减少pdr{$pdrs}个", 'exchanges_pdr_reduce');
        $res[] = mlog($this->wx_user_id, 'pdrs', $data['num'], "增加pdrs{$data['num']}个", 'exchanges_pdrs_add');
        $res[] = Db::name('system_config')->where(['name' => 'pdrs_surplus'])->setDec('value', $data['num']);
        if (check_arr($res)) {
            Db::commit();
            $this->success('兑换成功');
        } else {
            Db::rollback();
            $this->error('兑换失败');
        }

    }


    //兑换参数
    public function getExchangeDetailParams()
    {
        $res = [];
        $res['downTime'] = strtotime(sysconf('pdrs_exchange')) - get_time();
        $res['pdrs_surplus'] = sysconf('pdrs_surplus');
        $res['exchange_scale'] = sysconf('exchange_scale');
        $res['submit_pdrs_fee'] = sysconf('submit_pdrs_fee');
        $res['transfer_pdrs'] = sysconf('transfer_pdrs');
        return $this->success($res);
    }

    //pdrs转出
    public function sellPdrsOut()
    {
        $data = input('post.');
        $validate = Validate::make([
            'num' => 'require',
            'paypassword' => 'require',
            'submit_link' => 'require|length:20'
        ], [
            'num.require' => 'num不能为空',
            'paypassword.require' => 'paypassword不能为空',
            'submit_link.require' => '提币格式不能为空',
            'submit_link.length' => '提币地址不正确',
        ]);
        $validate->check($data) || $this->error($validate->getError());
        if (md5($data['paypassword']) != $this->wx_user['paypassword']) $this->error('交易密码不正确');
        if ($data['num'] < 0) $this->error('提币数量不正确');
        if ($data['num'] < sysconf('min_pdrs_num')) $this->error("提币数量不能少于" . sysconf('min_pdrs_num'));
        if ($data['num'] > $this->wx_user['pdrs']) $this->error('PDRS数量不足');
        $submit_pdrs_fee = sysconf('submit_pdrs_fee');
        if ($submit_pdrs_fee > $this->wx_user['account_money']) $this->error('pdr不足');
        Db::startTrans();
        $res = [];
        $sumit_data = [
            'submit_link' => $data['submit_link'],
            'create_at' => get_time(),
            'total_fee' => $submit_pdrs_fee,
            'uid' => $this->wx_user_id,
            'num' => $data['num'],
        ];
        $res[] = mlog($this->wx_user_id, 'pdrs', -$data['num'], "提币减少PDRS{$data['num']}", 'pdrs_reduce_btb_out');
        $res[] = mlog($this->wx_user_id, 'account_money', -$submit_pdrs_fee, "提币扣除手续费{$submit_pdrs_fee}", 'pdr_withdraw_btb');
        $res['sell_record'] = Db::name('es_sell_pdrs_record')->insertGetId($sumit_data);

        if (check_arr($res)) {
            Db::commit();
            $this->success('提币成功');
        } else {
            Db::rollback();
            $this->error('提币失败');
        }
    }


    //pdrs互转
    public function transferByPdrs()
    {
        $data = input('post.');
        $validate = Validate::make([
            'num' => 'require|number',
            'paypassword' => 'require',
            'phone' => 'require'
        ], [
            'num.require' => 'num不能为空',
            'num.number' => '转账格式不正确',
            'paypassword.require' => 'paypassword不能为空',
            'phone.require' => 'phone不能为空',
        ]);
        $validate->check($data) || $this->error($validate->getError());
        $transferUserinfo = Db::name('store_member')->where(['phone' => $data['phone']])->find();
        if ($transferUserinfo['id'] == $this->wx_user_id) $this->error('不能给自己转账');
        if (empty($transferUserinfo)) $this->error('账户不存在');
        if (md5($data['paypassword']) != $this->wx_user['paypassword']) $this->error('交易密码不正确');
        if ($data['num'] < 0) $this->error('转账数量不正确');
        if ($data['num'] > $this->wx_user['pdrs']) $this->error('PDRS数量不足');
        $submit_pdrs_fee = sysconf('transfer_pdrs');
        if ($submit_pdrs_fee > $this->wx_user['account_money']) $this->error('pdr不足');
        Db::startTrans();
        $res = [];
        $res[] = mlog($this->wx_user_id, 'pdrs', -$data['num'], "转账减少PDRS{$data['num']}", 'pdrs_reduce_btb', 0, 1, $transferUserinfo['id']);
        $res[] = mlog($transferUserinfo['id'], 'pdrs', $data['num'], "转账增加PDRS{$data['num']}", 'pdrs_increase_btb', 0, 1, $this->wx_user_id);
        if ($submit_pdrs_fee > 0) {
            $res[] = mlog($this->wx_user_id, 'account_money', -$submit_pdrs_fee, "转账扣除手续费{$submit_pdrs_fee}", 'pdrs_transfer', 0, 1, $transferUserinfo['id']);
        }
        if (check_arr($res)) {
            Db::commit();
            $this->success('转账成功');
        } else {
            Db::rollback();
            $this->error('转账失败');
        }
    }


    //转账记录
    public function getPdrsRecord()
    {
        $result = Db::name('bags_log a')
            ->join('store_member b', 'a.fromid = b.id')
            ->where(['uid' => $this->wx_user_id])
            ->where('extends', 'in', 'pdrs_reduce_btb,pdrs_increase_btb')
            ->page($this->page, $this->max_page_num)
            ->order('a.create_time desc')
            ->select();
        foreach ($result as &$v) {
            $v['money'] = reserve_num($v['money']);
            $v['extends'] = get_extends_txt($v['extends']);
            $v['create_time'] = format_time($v['create_time']);
            $v['after_money'] = reserve_num($v['money'] + $v['before']);
        }
        $this->success($result);
    }


    //提币记录
    public function getPdrsToOutRecord()
    {
        $result = Db::name('es_sell_pdrs_record')
            ->where(['uid' => $this->wx_user_id])
            ->page($this->page, $this->max_page_num)
            ->order('create_at desc')
            ->select();
        foreach ($result as &$v) {
            $v['submit_link'] = substr_replace($v['submit_link'], "******", 15, 20);
            $v['num'] = reserve_num($v['num']);
            $v['status'] = $v['status'] ? '审核中' : '已处理';
            $v['create_at'] = format_time($v['create_at']);
        }
        $this->success($result);
    }



    /*****************************扫码转账功能结束*********************************/
    /*
     * $type 类型
     * $phone 手机号
     * */
    public
    function getSmsCode($type, $phone)
    {
        return \Cache::pull($type . getips() . $phone);
    }

    /*
     * @param $type 类型
     * @param $code 验证码
     * @phone $phone 手机号
     * */
    public
    function setSmsCode($type, $code, $phone)
    {
        return \Cache::set($type . getips() . $phone, $code);
    }



    public function saveinfo()
    {
        $post = request()->post();
        if($post['carid']=='')
        {
            $this->error('请输入车牌号');
        }

        Db::startTrans();


        $res[] = Db::name('store_member')->where(['id' => $this->wx_user_id])->update(['carid' => $post['carid'],
            'phone'=>$post['phone'],
            'truename'=>$post['truename'],
            'sheng' => $post['sheng']
            ]);
        $re[] = Db::name('store_member_carid')->insert(['uid' => $this->wx_user_id,'sheng'=>$post['sheng'],'carid' => $post['carid'],'addtime' => date('Y-m-d H:i:s',time())]);

        if (check_arr($res) && check_arr($re)) {
            Db::commit();
            $this->success('完善成功');
        } else {
            Db::rollback();
            $this->error('完善失败');
        }
    }

    public function getProvince()
    {
        $result = Db::name('sys_address')->where('area_parent_id', 0)->where("simple_name<>''")->select();

        $this->success('', $result);
    }

}



